package com.util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author wangjg
 * @date 2023/11/1 15:15
 * @Description: 数据库连接工具类
 */
public class DbUtil {
    public Connection getCon() throws Exception {
        String driverName = "com.mysql.cj.jdbc.Driver";
        String userName ="root";
        String userPwd = "123456";
        String dbName = "db_dorm";
        String url = "jdbc:mysql://127.0.0.1:3306/"+dbName+"?useSSL=false&serverTimezone=UTC&userUnicode=true&characterEncoding=UTF-8";
        Class.forName(driverName);
        return DriverManager.getConnection(url,userName,userPwd);
    }

    public void closeCon(Connection con) throws Exception {
        if(con!=null) {
            con.close();
        }
    }

    /**
     * main方法测试数据库连接是否正常
     * @param args  入参
     */
    public static void main(String[] args) {
        DbUtil dbUtil = new DbUtil();
        try {
            Connection con = dbUtil.getCon();
            System.out.println("获取数据库连接成功：" + con.toString());
        } catch (Exception e) {
            System.out.println("获取数据库连接失败");
            e.printStackTrace();
        }
    }
}
